package systems
{
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	
	/**
	 * @author Humberto Anjos
	 */
	public class Input 
	{
		public var _active:Object
		private var _callbacks:Array
		private var _main:Main
		
		public function Input(main:Main) 
		{
			_main = main
			
			start()
		}
		
		public function addEventListener(callback:Function):void {
			_callbacks.push(callback)
		}
		
		public function start()
		{
			_active = new Object()
			_callbacks = []
			
			_main.stage.addEventListener(KeyboardEvent.KEY_DOWN, press, false, 0, true)
			_main.stage.addEventListener(KeyboardEvent.KEY_UP, release, false, 0, true)
		}
		
		public function clear()
		{
			_active = new Object()
			_callbacks.length = 0
			
			_main.stage.removeEventListener(KeyboardEvent.KEY_DOWN, press)
			_main.stage.removeEventListener(KeyboardEvent.KEY_UP, release)
		}
		
		private function press(e:KeyboardEvent):void
		{
			switch(e.keyCode) {
				case Keyboard.D:
					_active.right = true
					break
				case Keyboard.A:
					_active.left = true
					break
				case Keyboard.W:
					_active.up = true
					break
				case Keyboard.S:
					_active.down = true
					break
				case Keyboard.L:
					dispatch("toggleAnimation")
					break
				case Keyboard.K:
					_active.shoot = true
					break
			}
		}
		
		private function release(e:KeyboardEvent):void 
		{
			switch(e.keyCode) {
				case Keyboard.D:
					_active.right = false
					break
				case Keyboard.A:
					_active.left = false
					break
				case Keyboard.W:
					_active.up = false
					break
				case Keyboard.S:
					_active.down = false
					break
				case Keyboard.K:
					_active.shoot = false
					break
			}
		}
		
		protected function dispatch(event:String)
		{
			for each(var callback in _callbacks) {
				callback(event)
			}
		}
		
		public function get active():Object { return _active; }
	}
}